package com.sailorj.itools.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.project.Project;
import com.sailorj.itools.constants.SailorjConfigConstants;
import com.sailorj.itools.utils.CamelCaseUtils;
import com.sailorj.itools.utils.Logger;
import org.apache.http.util.TextUtils;

/**
 * Project : 将下划线的词转为驼峰
 * 2023年7月10日
 */
public class CamelCaseAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent event) {

        // 获取当前项目对象
        final Project project = event.getProject();

        Logger.init(SailorjConfigConstants.title, Logger.DEBUG);

        //获取编辑器
        Editor mEditor = event.getData(PlatformDataKeys.EDITOR);
        if (mEditor == null) {
            Logger.info("编辑器获取失败");
            return;
        }

        //获取选择器：描述光标选中的文本段
        SelectionModel model = mEditor.getSelectionModel();
        String selectText = model.getSelectedText();
        if (TextUtils.isEmpty(selectText)) {
            Logger.info("未选中文字");
            return;
        }
        // 替换选中文本
        Document document = mEditor.getDocument();
        // 文本开始下标,从第一行的0开始算例：458
        int selectionStart = model.getSelectionStart();
        // 文本结束下标,从第一行的0开始算例：465
        int selectionEnd = model.getSelectionEnd();

        final CaretModel caretModel = mEditor.getCaretModel();
        final Caret primaryCaret = caretModel.getPrimaryCaret();
        // 转换
        String camelCase;
        if (selectText.contains("_")) {
            camelCase = CamelCaseUtils.camelCase(selectText);
        } else {
            camelCase = CamelCaseUtils.convert(selectText);
        }
        Runnable runnable = () -> {
            document.deleteString(selectionStart, selectionEnd);
            document.insertString(selectionStart, camelCase);

            primaryCaret.moveToOffset(selectionStart + camelCase.length());
        };
        WriteCommandAction.runWriteCommandAction(project, runnable);
        Logger.showPopupWindow(mEditor, "转换成功！");
    }

}
